package org.springframework.web.servlet.ajax.json;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.servlet.http.HttpServletResponse;

/**
 * @author Charles Tassoni
 */

public class HttpServletResponseProxy implements InvocationHandler{

	private HttpServletResponse delegate;
	private StringBuffer buf;

	private HttpServletResponseProxy(HttpServletResponse delegate, StringBuffer buf){
		this.delegate = delegate;
		this.buf = buf;
	}

	public static HttpServletResponse newInstance(HttpServletResponse delegate, StringBuffer buf) {
		Class[] interfaces = {HttpServletResponse.class};
		return (HttpServletResponse) Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
				interfaces,
				new HttpServletResponseProxy( delegate, buf));
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		if(method.getName().equals("getWriter"))
			return  new HoldsContentPrintWriter(this.delegate.getWriter(), this.buf);
		else
			return method.invoke(this.delegate, args);
	}

}
